<script setup lang="ts">
import { deleteRoleAPI, getRoleListAPI, getRolePermissionsAPI, getRoleUserDataAPI, permissionsTreeAPI } from '@/apis/systemRole';
import type { permissionsTreeType, RoleItemType, RoleUserItemType } from '@/types/systemRole';
import { ref, watch } from 'vue';
import gege from '@/assets/caixukun.svg' // 哥哥
import gegeActive from '@/assets/caixukun-active.svg' // 高亮哥哥
import { ElMessage, ElMessageBox, type TreeInstance } from 'element-plus';
import { useRouter } from 'vue-router';


// 获取所有角色列表 ----------
const roleList = ref<RoleItemType[]>([])
const getRoleList = async () => {
  const res = await getRoleListAPI()
  activeIndex.value = 0
  roleList.value = res.data
  activeRoleId.value = roleList.value[0].roleId
}

// 右侧tab栏
const activeName = ref<string>('tree')

// 角色列表高亮切换
const activeIndex = ref<number>(0)

// 获取权限树形数据 ----------
const permissionsTree = ref<permissionsTreeType[]>([])
const getPermissionsTree = async () => {
  const res = await permissionsTreeAPI()
  permissionsTree.value = res.data
}

// 获取当前角色的权限和分配人数
const userTotal = ref<number>(0) // 当前角色关联的用户数
const checkedKeys = ref<number[][]>([]) // 当前角色的权限
const getRolePermissions = async (roleId: string) => {
  const res = await getRolePermissionsAPI(roleId)
  checkedKeys.value = res.data.perms
  userTotal.value = res.data.userTotal

  return res.data // 返回当前角色的权限和分配人数 用于重置权限用
}

// 获取角色关联的用户列表
const roleUserParams = ref<{ page: number, pageSize: number }>({
  page: 1,
  pageSize: 5,
})
const roleUserList = ref<RoleUserItemType[]>([]) // 列表
const getRoleUserData = async (roleId: string, params: { page: number, pageSize: number }) => {
  const res = await getRoleUserDataAPI(roleId, params)
  roleUserList.value = res.data.rows
}

// 依次获取所有数据 ----------
const getAll = async () => {
  await getRoleList()
  await getPermissionsTree()
  getRolePermissions(roleList.value[0].roleId!)
  getRoleUserData(roleList.value[0].roleId!, roleUserParams.value)
}
getAll()

const treeRefs = ref<TreeInstance[]>() // 树形结构ref ------------------

// 角色切换 ---
const activeRoleId = ref<string>()
const roleChange = async (roleId: string, index: number) => {
  if (activeIndex.value === index) return // 点击当前角色，退出函数，防止无用请求

  activeIndex.value = index
  activeRoleId.value = roleId
  
  roleUserParams.value.page = 1
  roleUserParams.value.pageSize = 5

  const res = await getRolePermissions(roleId) // async函数返回的是一个pormise对象，成功的结果就是return的值
  getRoleUserData(roleId, roleUserParams.value)
  // 重新设置选中权限
  treeRefs.value!.forEach((item, index) => {
    item.setCheckedKeys(res.perms[index])
  })
}

// 监听右侧tab栏切换
watch(activeName ,() => {
  if (activeName.value === 'tree') return
})

const router = useRouter()

// 编辑角色跳转
const editGo = (roleId: string) => {
  router.push({
    name: 'addRole',
    params: { id: roleId },
  })
}

// 删除角色
const deleteRole = async (roleId: string) => {
  await ElMessageBox.confirm('此操作将永久删除该角色, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })

  const res = await deleteRoleAPI(roleId)
  if (res.code === 10000) {
    ElMessage.success('删除成功')
    getAll()
  } else {
    ElMessage.error(res.msg)
  }
}

</script>

<template>
  <div class="role-container">
      <div class="left-wrapper" style="height: 100%">
        <el-scrollbar height="650px">
          <!-- 左侧角色列表 -->
          <div
            class="role-item"
            v-for="(item, index) in roleList"
            :key="item.roleId"
            @click="roleChange(item.roleId!, index)"
            :class="{ active: activeIndex === index }"
          >
            <!-- 角色名称 -->
            <el-tooltip
              class="box-item"
              effect="dark"
              :content="item.remark"
              placement="top"
              :disabled="!item.remark"
              :show-after="500"
            >
              <div class="role-info">
                <img :src="activeIndex === index ? gegeActive : gege" class="icon" />
                {{ item.roleName }}
              </div>
            </el-tooltip>
            
            <!-- 更多操作 -->
            <div class="more">
              <!-- 下拉框 -->
              <el-dropdown ref="dropdownRef" trigger="click">
                <span class="el-dropdown-link">
                  <img src="@/assets/more.svg" class="icon" />
                </span>
                <!-- 下拉框内容 -->
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item @click="editGo(item.roleId)" v-permission="'sys:role:add_edit'">编辑角色</el-dropdown-item>
                    <el-dropdown-item style="color: red;" @click="deleteRole(item.roleId)" v-permission="'sys:role:remove'">删除</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </div>
        </el-scrollbar>
        <el-button class="addBtn" size="small" @click="$router.push('/addRole')" v-permission="'sys:role:add_edit'">添加角色</el-button>
      </div>
    
    <!-- 右侧权限和成员 -->
    <div class="right-wrapper">
      <!-- tab栏组件 -->
      <el-tabs v-model="activeName">
        <!-- 权限设置 -->
        <el-tab-pane label="权限设置" name="tree">
          <div class="tree-wrapper">
            <div v-for="(item, index) in permissionsTree" :key="item.id" class="tree-item">
              <div class="tree-title"> {{ item.title }} </div>
                <!-- <el-tree
                  :data="" 树形结构数据
                  :props="{ label: '', disabled: }" 树形每个结构的属性 label 标题 disabled 是否禁用
                  show-checkbox 树形结构复选框
                  default-expand-all 默认展开所有节点
                  node-key="" 唯一标识
                  :default-checked-keys="" 默认选中的节点
                  ref="treeRefs"
                /> -->
                <el-tree
                  ref="treeRefs"
                  :data="item.children"
                  show-checkbox
                  default-expand-all
                  node-key="id"
                  :props="{ label: 'title', disabled: () => true }"
                  :default-checked-keys="checkedKeys[index]"
                />
            </div>
          </div>
        </el-tab-pane>
        <!-- 成员管理 -->
        <el-tab-pane :label="`成员管理(${userTotal})`" name="user">
          <!-- 成员列表 -->
          <div class="user-wrapper">
            <el-table :data="roleUserList">
              <el-table-column type="index" width="250" label="序号" />
              <el-table-column prop="name" label="员工姓名" />
              <el-table-column prop="userName" label="登录账号" />
            </el-table>
          </div>
          <!-- 分页 -->
          <div class="page-container" style="float: right; margin-right: 25px;">
            <el-pagination
              layout="total, prev, pager, next, sizes" 
              :page-sizes="[2, 5, 10, 20, 50]"
              :total="userTotal"
              v-model:current-page="roleUserParams.page"
              v-model:page-size="roleUserParams.pageSize"
              @change="getRoleUserData(activeRoleId!, roleUserParams)"
            />
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<style scoped lang="scss">
.role-container {
  display: flex;
  font-size: 14px;
  background-color: #fff;

  .left-wrapper {
    width: 200px;
    border-right: 1px solid #e4e7ec;
    padding: 4px;
    text-align: center;

    .role-item {
      position: relative;
      height: 56px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 0 20px;
      cursor: pointer;

      &.active {
        background: #edf5ff;
        color: #4770ff;
      }
    }

    .role-info {
      display: flex;
      align-items: center;

      .icon {
        margin-right: 10px;
        width: 20px;
      }
    }

    .more {
      display: flex;
      align-items: center;
      .icon {
          width: 15px;
        }
    }

    .addBtn {
      width: 100%;
      margin-top: 20px;
      height: 40px;
      font-size: 18px;
      border: 2px solid #e4e7ec;
    }
  }

  .right-wrapper {
    flex: 1;

    .tree-wrapper {
      display: flex;
      justify-content: space-between;

      .tree-item {
        flex: 1;
        border-right: 1px solid #e4e7ec;
        padding: 0px 4px;
        text-align: center;

        .tree-title {
          background: #f5f7fa;
          text-align: center;
          padding: 10px 0;
          margin-bottom: 12px;
        }
      }
    }

    :deep() .el-tabs__nav-wrap {
      padding-left: 20px;
    }

    .user-wrapper {
      padding: 20px;
    }
  }
}
</style>
